package com.appspot.checkflames.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.FacebookException;
import com.restfb.FacebookJsonMappingException;
import com.restfb.Parameter;
import com.restfb.types.Post;
import com.restfb.types.User;

import static com.appspot.checkflames.constants.CheckFlamesConstants.*;

public class Publisher extends HttpServlet {

	/**
	 * Generated serial version uid.
	 */
	private static final long serialVersionUID = -582154064608855865L;
	
	private static final Logger LOGGER = Logger.getLogger(Publisher.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String accessToken = (String)req.getSession().getAttribute(ACCESS_TOKEN_PARAM);
		if(accessToken == null) {
			resp.sendRedirect("/checkflames/");
			return;
		}
		FacebookClient client = new DefaultFacebookClient(accessToken);
		User me = null;
		try {
			me = client.fetchObject("me", User.class);
		} catch(Exception e) {
			LOGGER.error("Error in fetching object");
		}
		if(me == null) {
			resp.sendRedirect("/checkflames/");
			return;
		}
		
		String friendId = req.getParameter(SELECTED_FRIEND_ID);
		User selectedFriend = null;
		try {
			selectedFriend = client.fetchObject(friendId, User.class);
		} catch (FacebookException e1) {
			LOGGER.error("Error while retreiving facebook details", e1);
		}
		
		String messageToMe = "I tried for calculating FLAMES with "
				+ selectedFriend.getName()
				+ " Hope everyone will enjoy by calculating for their secret friends!!\n http://apps.facebook.com/check_flames/";
		
		String myDetails = (String) req.getSession().getAttribute(MYDETAILS);
		String messageToFriend = myDetails
				+ " tried to calculate FLAMES with you! Curious to know the result?! You can try the "
				+ "application!! All the best! \n http://apps.facebook.com/check_flames/";
		
		Post myPostResult = null; 
		Post friendsPost = null;
		try {
			myPostResult = client.publish("me/feed", Post.class, Parameter.with("message", messageToMe));
			friendsPost = client.publish(friendId +"/feed", Post.class, Parameter.with("message", messageToFriend));
			
		} catch (FacebookJsonMappingException e) {
			LOGGER.error("Error while parsing the post response", e);
		} catch (FacebookException e) {
			LOGGER.error("Error while fetching from facebook" ,e);
		}
		resp.sendRedirect("/checkflames/");
	}
	
}
